# 协程：微线程
# 进程 > 线程 > 协程
# Process  Thread  生成器完成
import time
from greenlet import greenlet


def task1():
    for i in range(3):
        print("A" + str(i))
        yield
        time.sleep(1)


def task2():
    for i in range(3):
        print("B" + str(i))
        yield
        time.sleep(2)


if __name__ == '__main__':
    g1 = task1()
    g2 = task2()

    while True:
        try:
            next(g1)
            next(g2)
        except:
            break


# greenlet 完成协程任务
def a():       # 任务A
    for i in range(5):
        print("A" + str(i))
        gb.switch()
        time.sleep(0.1)


def b():      # 任务B
    for i in range(5):
        print("B" + str(i))
        gc.switch()
        time.sleep(0.1)


def c():      # 任务C
    for i in range(5):
        print("C" + str(i))
        ga.switch()
        time.sleep(0.1)


if __name__ == "__main__":
    ga = greenlet(a)
    gb = greenlet(b)
    gc = greenlet(c)

    ga.switch()       # 只运行任务A的部分


# gevent模块
import gevent
from gevent import monkey
monkey.patch_all()


def a():
    for i in range(5):
        print("A" + str(i))
        time.sleep(0.1)


def b():
    for i in range(5):
        print("B" + str(i))
        time.sleep(0.1)


def c():
    for i in range(5):
        print("C" + str(i))
        time.sleep(0.1)


if __name__ == "__main__":
    g1 = gevent.spawn(a)
    g2 = gevent.spawn(b)
    gc = gevent.spawn(c)

    g1.join()
    g2.join()
    gc.join()
print("---------------")
